package com.enjoy.ui;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.enjoy.R;
import com.enjoy.utils.MyPoiOverlay;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;

import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class FindPlace extends Activity {
	BMapManager mBMapMan = null;
	MapView mMapView = null;
	MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	Button bt_search = null; // 搜索按钮
	MapController mMapController = null;
	ListView mSuggestionList = null;
	public static String mStrSuggestions[] = {};

	public MKMapViewListener mMapListener = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init("DE77636811AB41F0723CF668260EA75930D202A3", null);
		setContentView(R.layout.findplace);

		bt_search = (Button) findViewById(R.id.findplace_search);
		mMapView = (MapView) findViewById(R.id.findplace_bmapView);

		bt_search.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				LayoutInflater inflater = getLayoutInflater();
				final View layout = inflater.inflate(R.layout.findplace_dialog,
						(ViewGroup) findViewById(R.id.findplace_dialog));
				
			
				
				AlertDialog.Builder builder = new AlertDialog.Builder(
						FindPlace.this).setView(layout);
				
				
				
				builder.setPositiveButton("搜索",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								EditText et_city = (EditText) layout.findViewById(R.id.findplace_dialog_ed_city);
								EditText et_place = (EditText) layout.findViewById(R.id.findplace_dialog_ed_place);
								
								String city = et_city.getText().toString();
								String place = et_place.getText().toString();

								mSearch.poiSearchInCity(city, place);
								dialog.dismiss();
							}
						});
				
				builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog,int which) {
						dialog.dismiss();
					}
				});
				builder.show();

			}
		});

		initMapView();

		

		mSearch = new MKSearch();
		mSearch.init(mBMapMan, new MKSearchListener() {

			@Override
			public void onGetPoiDetailSearchResult(int type, int error) {
				if (error != 0) {
					Toast.makeText(FindPlace.this, "抱歉，未找到结果",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(FindPlace.this, "成功，查看详情页面",
							Toast.LENGTH_SHORT).show();
				}
			}

			public void onGetPoiResult(MKPoiResult res, int type, int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(FindPlace.this, "抱歉，未找到结果",
							Toast.LENGTH_LONG).show();
					return;
				}
				// 将地图移动到第一个POI中心点
				if (res.getCurrentNumPois() > 0) {
					// 将poi结果显示到地图上
					MyPoiOverlay poiOverlay = new MyPoiOverlay(FindPlace.this,
							mMapView, mSearch);
					poiOverlay.setData(res.getAllPoi());

					mMapView.getOverlays().clear();
					mMapView.getOverlays().add(poiOverlay);
					
					
					mMapView.refresh();
					// 当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空
					for (MKPoiInfo info : res.getAllPoi()) {
						if (info.pt != null) {
							Log.i("info:", info.name);
							Log.i("loction", info.pt.getLatitudeE6() + "++"
									+ info.pt.getLongitudeE6());
							mMapView.getController().animateTo(info.pt);
							break;
						}
					}
				} else if (res.getCityListNum() > 0) {
					String strInfo = "在";
					for (int i = 0; i < res.getCityListNum(); i++) {
						strInfo += res.getCityListInfo(i).city;
						strInfo += ",";
					}
					strInfo += "找到结果";
					Toast.makeText(FindPlace.this, strInfo, Toast.LENGTH_LONG)
							.show();
				}
			}

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
				if (arg1 != 0 || res == null) {
					Toast.makeText(FindPlace.this, "抱歉，未找到结果",
							Toast.LENGTH_LONG).show();
					return;
				}
				int nSize = res.getSuggestionNum();
				mStrSuggestions = new String[nSize];

				for (int i = 0; i < nSize; i++) {
					mStrSuggestions[i] = res.getSuggestion(i).city
							+ res.getSuggestion(i).key;
				}
				ArrayAdapter<String> suggestionString = new ArrayAdapter<String>(
						FindPlace.this, android.R.layout.simple_list_item_1,
						mStrSuggestions);
				mSuggestionList.setAdapter(suggestionString);
				Toast.makeText(FindPlace.this, "suggestion callback",
						Toast.LENGTH_LONG).show();

			}

		});

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();

		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onDestroy();
	}

	public void initMapView() {
		mMapView.setLongClickable(true);
		mMapController = mMapView.getController();
		GeoPoint point = new GeoPoint((int) (31.233574 * 1E6),
				(int) (121.41037 * 1E6));
		// 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
		mMapController.setCenter(point);// 设置地图中心点
		
		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				// Log.d("hjtest", "hjtest"+"onMapMoveFinish");
			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(FindPlace.this);
				final MapPoi mp = mapPoiInfo;
				
				builder.setMessage(mapPoiInfo.strText+"\n确定是这里");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent();
				 				intent.putExtra("longitude",(float)mp.geoPt.getLongitudeE6()/1000000+"");
				 				
				 				Log.i("longitude",(float)mp.geoPt.getLongitudeE6()/1000000+"");
				 				intent.putExtra("latitude",(float)mp.geoPt.getLatitudeE6()/1000000+"");
				 				Log.i("latitude",(float)mp.geoPt.getLatitudeE6()/1000000+"");
				 				intent.putExtra("placename", mp.strText);
				 				Log.i("placename",mp.strText);
				 				
				 				intent.setClass(FindPlace.this, CreateEvent.class);
				 				startActivity(intent);
							}
						});
				
				builder.setNegativeButton("取消",null);
				builder.show();
				
//				String title = "";
//				if (mapPoiInfo != null) {
//					title = mapPoiInfo.strText;
//					Toast.makeText(
//							FindPlace.this,
//							title + mapPoiInfo.geoPt.getLatitudeE6() + ":::"
//									+ mapPoiInfo.geoPt.getLongitudeE6(),
//							Toast.LENGTH_SHORT).show();
//				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				// Log.d("hjtest", "hjtest"+"onMapAnimationFinish");

			}
		};
		
		
		
		mMapView.regMapViewListener(mBMapMan, mMapListener);

		mMapController.setZoom(12);
		mMapController.enableClick(true);
		mMapView.setBuiltInZoomControls(true);
	}
}
